using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

/* 
----------------------------------------------------------------------------
【调用方法延迟的类】

每次调用，会自动生成一个叫[ActionUtils]GameObject，然后自动挂载上去，实例化

延迟操作:
1、
ActionUtils.Instance.DelayToCall(MethodName,3)

2、匿名调用
ActionUtils.Instance.DelayToCall( ()=>{xxxxxxxxxxx} ,3)
----------------------------------------------------------------------------
 */
public class ActionUtils : MonoBehaviour
{

    // -----------------------实例化 START----------------------
    private static ActionUtils temp;
    
    public static ActionUtils Instance
    {
        get
        {
            if (temp == null)
            {
                temp = FindObjectOfType<ActionUtils>();

                if (temp == null) temp = new GameObject("ActionUtils").AddComponent<ActionUtils>();

            }

            return temp;
        }
    }
    // -----------------------实例化 END----------------------

    public static Dictionary<Action, float> actionDic = new Dictionary<Action, float>();

    // 注册多个事件
    public void RigisterAction(Action action, float time)
    {
        actionDic.Add(action, time);
    }
    
    // 清除所有事件
    public void ClearActions()
    {
        actionDic.Clear();
    }
    

    // 执行事件流上的所有事件
    public void CallActions()
    {
        List<Action> theActionList = new List<Action>(actionDic.Keys);
        List<float> theTimeList = new List<float>(actionDic.Values);
        theActionList[0]();
        for (int i = 1; i < theActionList.Count; i++)
        {
            StartCoroutine(DelayToCallIEnumerator(theActionList[i], Sum(theTimeList, i - 1)));
        }
    }
    
    
    public void CallActions(bool IsClear)
    {
        CallActions();
        if (IsClear)
        {
            ClearActions();
        }
    }
    
    float Sum(List<float> list, int index)
    {
        float x = 0;
        for (int i = 0; i < list.Count; i++)
        {
            if (i <= index)
            {
                x += list[i];
            }
        }
        return x;
    }


    // 单个延迟事件
    public void DelayToCall(Action action, float time)
    {
        StartCoroutine(DelayToCallIEnumerator(action, time));
    }

    private IEnumerator DelayToCallIEnumerator(Action action, float time)
    {
        yield return new WaitForSeconds(time);
        action();
    }
}